Skip to content

Conversation

@forfudan
Copy link
Collaborator

Adds NDAxisIter struct and iter_by_axis method that iterate array by any axis. In each iteration, the iterator yields a 1-d array by specified axis. It is useful when we want to write a universal function to reduce the array by certain axis.

Example:

from numojo.prelude import *
var a = nm.arange[i8](24).reshape(Shape(2, 3, 4))
print(a)
for i in a.iter_by_axis(axis=0):
    print(String(i))

This prints:

[[[ 0  1  2  3]
    [ 4  5  6  7]
    [ 8  9 10 11]]
    [[12 13 14 15]
    [16 17 18 19]
    [20 21 22 23]]]
3D-array  Shape(2,3,4)  Strides(12,4,1)  DType: i8  C-cont: True  F-cont: False  own data: True
[ 0 12]
[ 1 13]
[ 2 14]
[ 3 15]
[ 4 16]
[ 5 17]
[ 6 18]
[ 7 19]
[ 8 20]
[ 9 21]
[10 22]
[11 23]

Another example:

from numojo.prelude import *
var a = nm.arange[i8](24).reshape(Shape(2, 3, 4))
print(a)
for i in a.iter_by_axis(axis=2):
    print(String(i))

This prints:

[[[ 0  1  2  3]
    [ 4  5  6  7]
    [ 8  9 10 11]]
    [[12 13 14 15]
    [16 17 18 19]
    [20 21 22 23]]]
3D-array  Shape(2,3,4)  Strides(12,4,1)  DType: i8  C-cont: True  F-cont: False  own data: True
[0 1 2 3]
[4 5 6 7]
[ 8  9 10 11]
[12 13 14 15]
[16 17 18 19]
[20 21 22 23]
```.

@shivasankarka shivasankarka merged commit 68b5595 into Mojo-Numerics-and-Algorithms-group:pre-0.6 Feb 15, 2025
2 checks passed
@forfudan forfudan deleted the iter branch February 15, 2025 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants